﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebComponents.Data;
using WebComponents;
using WebComponents.Security;
using System.Net.Mail;
using GBIT.Web;

public partial class SendMail : UserControlBase {
  protected void Page_Load(object sender, EventArgs e) {
    if (Session["login"] == null)
      Response.Redirect("Login.aspx");
    txtMailTo.Text = ConvertType.ToString(Request.Params["Email"]);
    this.Title = "Gửi mail phản hồi";
  }
  public int Send(string from_email, string from_pass, string from_displayName, string to_email, string subject, string body) {
    MailMessage email = new MailMessage();
    email.To.Add(to_email);
    email.From = new MailAddress(from_email, from_displayName, System.Text.Encoding.UTF8);
    email.Subject = subject;
    email.SubjectEncoding = System.Text.Encoding.UTF8;
    email.Body = body;
    email.BodyEncoding = System.Text.Encoding.UTF8;

    email.IsBodyHtml = true;

    email.Priority = MailPriority.High;

    SmtpClient smtp = new SmtpClient();

    smtp.Credentials = new System.Net.NetworkCredential(from_email, from_pass);
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.Port = 587;

    smtp.Host = ConfigurationManager.AppSettings["SmtpServer"];

    smtp.EnableSsl = true;

    try {
      smtp.Send(email);
      return 1;
    } catch {
      return 0;
    }
  }
  protected void btnGui_Click(object sender, EventArgs e) {
    string pass = ConfigurationManager.AppSettings["MailPassword"];
    string[] arr = txtMailTo.Text.Split(',');
    string thanhCong = "Gửi mail thành công tới các email : ";
    string thatBai = "<span style='color: red'>Gửi mail không thành công tới các email :";
    bool flag = false;
    foreach (string mail in arr) {
      if (mail != "" && mail.Contains("@")) {
        int kq = Send(ConfigurationManager.AppSettings["MailAccount"], pass, "", mail.Trim(), txtTitle.Text, txtNContent.Value);
        if (kq == 1) {
          thanhCong += mail;
        } else {
          flag = true;
          thatBai += mail;
        }
      }
    }
    if (flag == true) {
      lblMsg.Text = thanhCong + "<br/>" + thatBai + "</span>";
      Security.ShowClientMessage(Page, "Địa chỉ Email không tồn tại vui lòng kiểm tra lại");
    } else {
      lblMsg.Text = "<span style='color: blue'>Gửi mail thành công!</span>";
      Security.ShowClientMessage(Page, "Gửi mail phản hồi thành công", "?tabid=0");
    }
  }
}
